"""其他时间维度的后处理脚本"""
import numpy as np

from air_web.dw.data_mapping import TimeDimension
from air_web.dw.dws_common import AggCommon


class MaxTime(AggCommon):
    """获取当天每个区域最大点"""

    def __init__(
        self,
        logger,
        task,
        start_time,
        end_time,
        step,
        step_dict,
        timedelta,
        rewrite,
    ):
        super().__init__(
            logger,
            task,
            start_time,
            end_time,
            step,
            step_dict,
            rewrite=rewrite,
        )

    def area_agg(self):
        """根据区域和时间进行聚合"""
        sql = """select org_no, data_time as max_time, DATE(data_time) as compute_date, 
                        {select_fields}
                 from {source_table}
                 where data_time between '{start_time}' and '{end_time}' 
                   and type_id = 0 and is_day_max=1
              """.format(
            select_fields=",".join(self.rename.keys()),
            source_table=self.source_table,
            start_time=self.start_time,
            end_time=self.end_time,
        )
        self.res_df = self.sql_engine.query(sql)

    def main(self):
        """主函数"""
        self.logger.info(
            "正在处理task_id:{},step:{},star_time:{} ...".format(
                self.task_id, self.step, self.start_time
            )
        )
        self.area_agg()
        self.rename_agg_indicators()
        self.save_data_to_table()


class AggTime(AggCommon):
    """其他时间维度的聚合"""

    def __init__(
        self,
        logger,
        task,
        start_time,
        end_time,
        step,
        step_dict,
        timedelta,
        rewrite,
    ):
        super().__init__(
            logger,
            task,
            start_time,
            end_time,
            step,
            step_dict,
            timedelta=timedelta,
            rewrite=rewrite,
        )

    def get_time_display_name(self):
        """获取页面显示的时间形式"""
        # start_time = datetime.strptime(self.start_time, '%Y-%m-%d %H:%M:%S')
        if self.timedelta == TimeDimension.DAY:
            time_display_name = self.start_time.date()
        elif self.timedelta == TimeDimension.WEEK:
            time_display_name = self.start_time.isocalendar()[1]
        elif self.timedelta == TimeDimension.MONTH:
            time_display_name = self.start_time.month
        elif self.timedelta == TimeDimension.QUARTER:
            time_display_name = (self.start_time.month - 1) // 3 + 1
        elif self.timedelta == TimeDimension.YEAR:
            time_display_name = self.start_time.year
        else:
            time_display_name = self.start_time
        return time_display_name

    def get_agg_df(self):
        """从配置的表中读取数据"""
        group_cols = "org_no, org_name, ad_org_name, p_org_no, type_id, type_code, p_type_id"

        agg_sql = ""
        for field, agg_type in self.indicators.items():
            agg_sql = f"{agg_sql}, {agg_type}({field}) as {field}_{agg_type}"

        sql = """select {group_cols} {agg_sql}
                 from {source_table}
                 where data_time between '{start_time}' and '{end_time}'
                 group by {group_cols}
              """.format(
            group_cols=group_cols,
            agg_sql=agg_sql,
            source_table=self.source_table,
            start_time=self.start_time,
            end_time=self.end_time,
        )
        self.res_df = self.sql_engine.query(sql)
        self.res_df["data_time"] = self.start_time
        self.res_df["time_display_name"] = self.get_time_display_name()
        self.res_df = self.res_df.replace({np.nan: None})

    def main(self):
        """主函数"""
        self.logger.info(
            "正在处理task_id:{},step:{},star_time:{} ...".format(
                self.task_id, self.step, self.start_time
            )
        )
        self.get_agg_df()
        self.rename_agg_indicators()
        self.save_data_to_table()
